package com.example.sourcesprng.jdk8._lambda._method_reference;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class MethodReferenceTest {

    public static void main(String[] args) {
        Date now = new Date();
        Supplier<Long> supplier = () -> {
            return now.getTime();
        };

        System.out.println(supplier.get());

        // now.getTime该方法已经存在了，可以直接通过方法引用来进行调用
        // 对象名::方法名
        supplier = now::getTime;

        List<Integer> ints = Arrays.asList(1, 2, 3, 4);
        ints.forEach(e -> System.out.println(e));
        ints.forEach(System.out::print);

        // 对象名::方法名
        MethodReferenceTest2 methodReferenceTest2 = new MethodReferenceTest2();
        ints.forEach(methodReferenceTest2::print1);

        // 类名::静态方法名
        ints.forEach(MethodReferenceTest2::print);

        // 类名::方法名
//        ints.forEach(MethodReferenceTest2::print);
        // 步骤一：使用lambda表达式，入参为String,返回值为：入参的长度
        Function<String, Integer> function = (String str) -> {
            return str.length();
        };
        // 步骤二：单入参，简化
        function = str -> {
            return str.length();
        };
        // 步骤三：str.length()方法已存在，可以简写方法引用的方式
        function = String::length;
        Integer hello_world = function.apply("hello world");
        System.out.println(hello_world);

        BiFunction<MethodReferenceTest2, String, String> biFunction = MethodReferenceTest2::print2;
        System.out.println(biFunction.apply(new MethodReferenceTest2(), "hello world"));

        // 类名::new
        Supplier<MethodReferenceTest2> supplier1 = MethodReferenceTest2::new;
        MethodReferenceTest2 methodReferenceTest21 = supplier1.get();
        System.out.println(methodReferenceTest21.print2("好人"));

        // 数组::new
        Function<Integer, String[]> function1 = String[]::new;
        String[] apply = function1.apply(10);
        System.out.println(apply.length);
    }

    public static void print(int a) {
        System.out.println(a);
    }
}
